package com.jzg.common.plugins.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Component;

import com.jfinal.kit.JsonKit;
import com.jfinal.log.Log;
import com.jzg.common.render.RenderBean;

@Component("ShiroFormFilter")
public class ShiroFormFilter extends FormAuthenticationFilter{
	protected final Log LOG = Log.getLog(getClass());
	

	/**
	 * 在访问controller前判断是否登录，返回json，不进行重定向。
	 * @param request
	 * @param response
	 * @return true-继续往下执行，false-该filter过滤器已经处理，不继续执行其他过滤器
	 * @throws Exception
	 */
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		try {
			HttpServletRequest httpServletRequest = (HttpServletRequest) request;
			HttpServletResponse httpServletResponse = (HttpServletResponse) response;
	        if (isLoginRequest(request, response)) {
	            if (isLoginSubmission(request, response)) {
	                return executeLogin(request, response);
	            } else {
	                return true;
	            }
	        } else {
	        	if(isAjaxRequest(httpServletRequest)) {
	        		RenderBean renderBean=new RenderBean();
					renderBean.setCode(401);
					renderBean.setMessage("登录超时，请重新登录!");
					httpServletResponse.setCharacterEncoding("UTF-8");
					httpServletResponse.setContentType("application/json");
					httpServletResponse.getWriter().write(JsonKit.toJson(renderBean));
	        	}else {
	    			this.setLoginUrl("sys/login");
	                saveRequestAndRedirectToLogin(request, response);
	        	}
	        }
		}catch (Exception e) {
			LOG.error(e.getMessage());
		}
		return false;
	}
	
	public static boolean isAjaxRequest(HttpServletRequest request) {
		String requestedWith = request.getHeader("x-requested-with");
		if (requestedWith != null && requestedWith.equalsIgnoreCase("XMLHttpRequest")) {
			return true;
		} else {
			return false;
		}
	}
}
